import 'dart:async';

Stream<String> generateMessages() async* {
  List<String> messages = ['Hello', 'Welcome', 'Goodbye'];
  for (var msg in messages) {
    await Future.delayed(const Duration(seconds: 1));
    yield msg;
  }
}

void processMessages() async {
  await for (var message in generateMessages()) {
    print('Processing: $message');
  }
}

void testCreateStream() {
  final controller = StreamController<int>();

  // 添加监听器
  controller.stream.listen((data) {
    print('Received: $data');
  });

  // 添加数据
  controller.sink.add(1);
  controller.sink.add(2);
  controller.sink.add(3);

  // 关闭流
  controller.close();
}

void main() {
  generateMessages().listen((message) {
    print(message);
  });

  processMessages();

  testCreateStream();

  // 每隔一秒发送一个数值
  Stream<int> periodicStream =
      Stream.periodic(const Duration(seconds: 1), (count) => count);
  periodicStream.listen((data) {
    print(data);
  });

  List<int> numbers = [1, 2, 3, 4, 5];

  // 使用 map 将每个数字乘以 2
  var doubledNumbers = numbers.map((number) => number * 2).toList();

  print(doubledNumbers); // 输出: [2, 4, 6, 8, 10]
}
